package org.alis.rpc.common.serializer.hessian;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import lombok.extern.slf4j.Slf4j;
import org.alis.rpc.common.serializer.Serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @author lc
 * @version v1.0.0
 * @date 2020/8/20 17:18
 * @className HessianSerializer.class
 */
@Slf4j
public class HessianSerializer implements Serializer {

    @Override
    public <T> byte[] serializer(T obj) {
        Hessian2Output ho = null;
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            ho = new Hessian2Output(os);
            ho.writeObject(obj);
            ho.flush();
            return os.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (Objects.nonNull(ho)) {
                try {
                    ho.close();
                } catch (IOException e) {
                    log.error("关闭hessian2输出流的时候发生异常,异常堆栈->", e);
                }
            }

        }

    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T deserializer(byte[] bytes, Class<T> clazz) {
        Hessian2Input hi = null;
        try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {
            hi = new Hessian2Input(is);
            return (T) hi.readObject();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (Objects.nonNull(hi)) {
                try {
                    hi.close();
                } catch (IOException e) {
                    log.error("关闭hessian2输入流的时候发生异常,异常堆栈->", e);
                }
            }
        }
    }

}
